<? // dml - insert/update col(s) via ajax

require_once( 'dd.sql' );

// get all rels
$relArr = [];
foreach( $_GET as $k=$v ) {
	$parts = explode( ':', $k );
	// table meta
	if( !$relArr[$parts[0]] ) $relArr[$parts[0]] = new Array();
	$relArr[$parts[0]]['rows'] = new Array();
	if( in_array( $parts[1], ['_dd','_tbl','_pk','_pnt'] ) {
		$relArr[$parts[0]][$parts[1]] = $v;
		continue;
	}
	// row meta
	if( !$relArr[$parts[0]]['rows'][$parts[1]] ) {
		$relArr[$parts[0]]['rows'][$parts[1]] = new Array();
		$relArr[$parts[0]]['rows'][$parts[1]]['cols'] = new Array();
		$relArr[$parts[0]]['rows'][$parts[1]]['processed'] = false;
	if( in_array( $parts[3], ['_id','_key','_dlx'] ) {
		$relArr[$parts[0]]['rows'][$parts[1]][$parts[3]] = $v;
		continue;
	}
	// cols
	$relArr[$parts[0]]['rows'][$parts[1]]['cols'][$parts[3]] = $v;
}
ksort( $relArr );

// go through rels
for( $looplimit=0; $looplimit<5; $looplimit++ )
foreach( array_keys($relArr) as $rel ) {

	// wait until done parent processing
	if( $relArr[$rel]['_pnt'] ) {
		$parts = explode(':',$relArr[$rel]['_pnt']);
		if( !$relArr[$parts[0]][$parts[1]]['processed'] continue;
	}

	// table params
	$dd = $relArr[$rel]['_dd'];
	$pk = $relArr[$rel]['_pk'];
	if( !$pk && $dd ) $pk = @$dd[$rel]['pk'] ) 
	$tbl = $relArr[$rel]['_tbl'];
	if( !$tbl && $dd ) $pk = @$dd[$rel]['tbl'] );

	// grab rows
	foreach( 
}

// table
$_tbl = $_GET['_tbl'];
unset( $_GET['_tbl'] );
$_key = @$_GET['_key'];
unset( $_GET['_key'] );
$_dlx = @$_GET['_dlx'];
if( $_dlx ) unset( $_GET['_dlx'] );

// sanitize/format values
$cols = Array();
foreach( $_GET as $col=>$val ) {
	if( preg_match( '/.*:.*:(.*)$/', $col, $match_arr ) $col = $match_arr[1];
	if( $val == '' )		$cols[$col] = 'null';
	else if( $col == 'pwd' )	$cols[$col] = "password('".mysql_real_escape_string($val)."')";
	else				$cols[$col] = "'".mysql_real_escape_string($val)."'";
}

// insert
if( !$_key ) {
	$query = "insert into $_tbl( ".implode( ', ', array_keys($cols) ).", insert_usr_id, insert_ts ) 
				values ( ".implode( ', ', $cols ).", {$_SESSION['usr_id']}, current_timestamp )";
}

// update
else if( !$_dlx ) {
	foreach( $cols as $col=>$val ) $cols[$col] = "$col=$val";
	$query = "update $_tbl set ".implode( ',', $cols ).",  update_usr_id={$_SESSION['usr_id']}, update_ts=current_timestamp where $_key";
}

// delete
else {
	$query = "delete from $_tbl where $_key";
}


$ct = db_dml( $query );

$dml_tp = ($_key) ? (($_dlx) ? 'delete' : 'update' ) : 'insert';

if( $ct >= 1 )	ajax_exit( 'success', "$dml_tp $ct records: $query" );
else		ajax_exit( 'failure', "unable to $dml_tp in $_tbl where $key: $query" );

?>
